<?php

namespace app\factory\logic;

use app\common\exception\LogicException;
use app\model\FactoryUser;
use think\facade\Db;

class FactoryUserLogic
{
    protected FactoryUser $model;
    protected int $factory_id;

    public function __construct()
    {
        $this->model = new FactoryUser();
        $this->factory_id = request()->factory_info['factory_id'];
    }

    /**
     * @Description 新增/编辑
     * @author: zj
     * @param mixed $Id
     * @param array $param
     * @time 2024/03/12 15:48:41
     * @return true
     */
    public function addEdit(mixed $Id, array $param)
    {
        Db::startTrans();
        try {
            $exist = $this->model->checkOutIdIsExist($this->factory_id,$Id);
            if ($exist) {
                $rule = [
                    'NickName' => 'max:50',
                    'UserName' => 'max:50',
                    'PassWord' => 'max:255',
                ];
                validate($rule)->check($param);

                $updateData = [];
                if ($param['NickName']) {
                    $updateData['nickname'] = $param['NickName'];
                }
                if ($param['UserName']) {
                    $username = $this->model->checkUserNameIsExist($this->factory_id,$param['UserName']);
                    if ($username && $username != $exist) {
                        throw new LogicException('用户名已存在');
                    }
                    $updateData['username'] = $param['UserName'];
                }
                if ($param['PassWord']) {
                    $updateData['password'] = $param['PassWord'];
                }
                $updateData['update_record_time'] = $param['RecordTime'];
                $updateData['update_time'] = request()->time();

                $this->model->where('out_id',$Id)
                    ->where('delete_time',$this->model::IS_DELETE_NO)
                    ->update($updateData);
            } else {
                $rule = [
                    'NickName' => 'require|max:50',
                    'UserName' => 'require|max:50',
                    'PassWord' => 'require|max:255',
                ];
                validate($rule)->check($param);

                $this->model->insert([
                    'factory_id' => $this->factory_id,
                    'out_id' => $Id,
                    'nickname' => $param['NickName'],
                    'username' => $param['UserName'],
                    'password' => $param['PassWord'],
                    'record_time' => $param['RecordTime'],
                    'update_record_time' => $param['RecordTime'],
                    'create_time' => request()->time(),
                    'update_time' => request()->time()
                ]);
            }

            Db::commit();
        }catch (\Exception $exception) {
            Db::rollback();
            throw new LogicException($exception->getMessage());
        }

        return true;
    }
}